package com.flying.box;

import java.util.Arrays;
import java.util.zip.DeflaterOutputStream;

/**
 * @author 刘鹏飞
 * @ClassName BoxCache
 * @Date 2024/12/21 09:17
 * @Created by 刘鹏飞
 * @Description 包装类的缓存
 * TODO:
 *  整型,char类型对应的包装类,在自动装箱时,对于-128~127之间值会进行缓存处理,目的是提高效率
 *  原理: 如果数据在-128~127之间,那么类加载时就已经为为该区间内的每个值穿件了对象,
 *  并将256个对象方法放到一个cache的数组中,,每次自动装箱的过程中先判断是否处于该区间,是-则直接获取数组中对应的包装类对象的引用.否=则通过new方法创建一个包装类对象
 */
public class BoxCache {

    public static void main(String[] args) {

        Integer x = 120;
        Integer y = 120;
        System.out.println(x == y);  // true
        System.out.println(x.equals(y));


        Integer m = 128;
        Integer n = 128;
        System.out.println(m == n);     // false   缓存问题
        System.out.println(m.equals(n));



        // 测试自定义包装类

        MyInteger myInteger = new MyInteger(12);

        MyInteger myInteger1 = MyInteger.valueOf(12);
        MyInteger myInteger2 = MyInteger.valueOf(12);

        MyInteger m3 = MyInteger.valueOf(128);
        MyInteger m4 = MyInteger.valueOf(128);
        System.out.println(myInteger1==myInteger2);
        System.out.println(m3==m4);


    }
}

class MyInteger {
    final int value;
    static final int LOW = -128;
    static final int HIGH = 127;

    private static MyInteger[] cache;


    static {
        cache=new MyInteger[HIGH-LOW+1];
        for (int i = 0; i < HIGH - LOW + 1; i++) {
            cache[i] = new MyInteger(LOW + i);
        }

        System.out.println(Arrays.toString(cache));

    }

    @Override
    public String toString() {
        return  ""+ value ;
    }

    MyInteger(int value) {
        this.value = value;
    }


    public int intValue() {
        return this.value;
    }


    public static MyInteger valueOf(int value) {
        if (value >= LOW && value <= HIGH) {
            return cache[value - LOW];
        }

        return new MyInteger(value);
    }

}


